package topic

import (
	"context"
	"fmt"
	"strconv"
	"strings"
	// "time"

	"mall/common/errorx"
	"mall/common/globalkey"
	"mall/common/mqueuex"
	// "mall/common/subscribex"
	"mall/service/backend/api/internal/lib/membertask"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/i18n"
	"mall/service/backend/common/utils/pointy"
	"mall/service/forum/rpc/forumclient"

	// "github.com/silenceper/wechat/v2/miniprogram/subscribe"
	"github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
	// "github.com/zeromicro/go-zero/core/service"
)

type UpdateTopicLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateTopicLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateTopicLogic {
	return &UpdateTopicLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateTopicLogic) UpdateTopic(req *types.UpdateForumTopicReq) (*types.BaseMsgResp, error) {
	if len(req.Ids) == 0 {
		return nil, errorx.Error(errorx.ERROR_FORUM_TOPIC_ID_REQUIRED, "")
	}

	var adminId uint64 = l.GetUserId()

	var userTaskForumQuestionGem string
	memberTaskMap := l.getMemberTaskMap()
	if memberTaskMap != nil {
		logrus.Info(fmt.Sprintf("UpdateTopic memberTaskMap: %+v", memberTaskMap))
		if memberTask, ok := memberTaskMap[mqueuex.UserTaskForumQuestion]; ok { // "forum_topic"
			if memberTask.Gems != nil && *memberTask.Gems > 0 {
				userTaskForumQuestionGem = strconv.FormatInt(int64(*memberTask.Gems), 10)
			}
		}
	}

	var ids []string
	for _, id := range req.Ids {
		ids = append(ids, strconv.FormatInt(int64(id), 10))
	}
	var modType int32 = globalkey.ForumModTypeTopic // 问题审核
	if req.Sticky != nil {
		modType = globalkey.ForumModTypeTopicSticky // 问题推荐
	}
	_, err := l.svcCtx.ForumRpc.BackendBatchUpdateTopic(l.ctx, &forumclient.BackendTopicListReq{
		Ids:       pointy.GetPointer(strings.Join(ids, ",")),
		Type:      pointy.GetPointer(uint32(modType)),
		Status:    req.Status,
		Sticky:    req.Sticky,
		Memo:      req.Memo,
		Extra:     req.Extra,
		Gems:      pointy.GetPointer(userTaskForumQuestionGem),
		UpdatedBy: pointy.GetPointer(adminId),
	})
	if err != nil {
		return nil, err
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
	}, nil
}

// func (l *UpdateTopicLogic) getMessages(noticeType int32, openId string, question *types.ForumMeta) []*subscribe.Message {
// 	var title string
// 	var tip string
// 	if noticeType == 1 {
// 		title = "已通过"
// 		tip = "积分奖励已发放"
// 	} else {
// 		title = "已驳回"
// 		tip = "请修改后再次提交审核"
// 	}
// 	var slug string = "问题补充说明未填写"
// 	if question.Value != "" {
// 		slug = question.Value
// 	}
// 	now := time.Now().Format("2006-01-02 15:04:05")
// 	if question.Url != "" {
// 		now = question.Url
// 	}

// 	return []*subscribe.Message{
// 		{
// 			ToUser:     openId,
// 			Page:       "pages/publicPage/message-page",
// 			TemplateID: subscribex.ForumPostModerationTemplateID,
// 			Data:       map[string]*subscribe.DataItem{
// 				"phrase5": {Value: title}, // 审核状态
// 				"thing1":  {Value: question.Key}, // 留言文章
// 				"thing2":  {Value: slug}, // 评论内容
// 				"date3":   {Value: now}, // 评论时间
// 				"thing4":  {Value: tip}, // 备注
// 			},
// 		},
// 	}
// }

// func (l *UpdateTopicLogic) SendNotificationWxMini(msg *subscribe.Message) {
// 	if l.svcCtx.Config.Mode != service.ProMode {
// 		msg.MiniprogramState = "developer"
// 	} else {
// 		msg.MiniprogramState = "formal"
// 	}

// 	err := l.svcCtx.MiniProgram.GetSubscribe().Send(msg)
// 	if err != nil {
// 		logrus.Info(fmt.Sprintf("Forum topics updated, send wechat mini subscription message failed, err: %+v, msg: %+v", err, msg))
// 	}

// 	return
// }

// func (l *UpdateTopicLogic) addCacheActivityFeed(ctx context.Context, feeds []*forumclient.ForumReviewGrade) error {
// 	if len(feeds) == 0 {
// 		return nil
// 	}

// 	sectionKey := cachex.ForumActivityFeed

// 	for _, feed := range feeds {
// 		_, err := l.svcCtx.BizRedis.ZaddCtx(ctx, sectionKey, feed.Id, strconv.FormatInt(feed.Id, 10))
// 		if err != nil {
// 			return err
// 		}
// 	}

// 	return l.svcCtx.BizRedis.ExpireCtx(ctx, sectionKey, l.svcCtx.Config.Query.ExpireTime)
// }

func (l *UpdateTopicLogic) GetUserId() uint64 {
	var userId uint64
	if val := l.ctx.Value("userId"); val != nil {
		if i, err := strconv.ParseInt(val.(string), 10, 64); err == nil {
			userId = uint64(i)
		}
	}

	return userId
}
func (l *UpdateTopicLogic) getMemberTaskMap() (map[string]*types.MemberTaskInfo) {
	memberTask := membertask.NewMemberTask(l.ctx, l.svcCtx)
	memberTaskList, err := memberTask.List()
	if err != nil {
		logrus.Info(fmt.Sprintf("UpdateTopic getMemberTaskMap err: %+v", err))
		return nil
	}

	if len(memberTaskList) > 0 {
		resp := make(map[string]*types.MemberTaskInfo)
		for _, v := range memberTaskList {
			if v.Slug != nil && len(*v.Slug) > 0 {
				resp[*v.Slug] = v
			}
		}

		return resp
	}

	return nil
}
